package chapter3to7.src.main.java.com.kaikeba.concurrent;

import lombok.SneakyThrows;

/**
 * @author 吴世凯
 * 邮箱：
 * 日期：3/21/2021
 * wait() and  notify() 经典 线程问题的核心 方法, 这个由操作系统提供实现；
 */
public class TwoThreadTwistDemo implements Runnable {

    private static int num =1 ;

    static  Object object = new Object();


    @Override
    public void run() {


        while (true) {
            synchronized (object) {  //object不能放在同步监视中, notify()和wait() 里面的方法必须是 同步代码块中的 变量;
                object.notifyAll();

                if (num < 100 ) {

                    try {
                        Thread.sleep(10 );
                        System.out.println(Thread.currentThread().getName() + "  -->  " + num);
                        num = num+1;
                        object.wait(); //会释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {

                    break;
                }

            }

        }

    }

    public static void main(String[] args) {

        Thread thread1 = new Thread(new TwoThreadTwistDemo());
        thread1.setName("AA");
        Thread thread2 = new Thread(new TwoThreadTwistDemo());
        thread2.setName("BB");
        thread1.start();
        thread2.start();


    }

}


// Exception in thread "BB" java.lang.IllegalMonitorStateException


